<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">幸福重工</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="账号"
        >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img v-if="codeUrl" :src="codeUrl" @click="getCode" class="login-code-img"/>
          <div v-else class="login-code-loading" @click="getCode">加载中...</div>
        </div>
      </el-form-item>
      <div class="login-code-tip">
        <span v-if="codeUrl">点击图片刷新验证码</span>
        <span v-else style="color: #F56C6C;">验证码加载失败，点击重试</span>
      </div>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="margin-top: 10px;">
          <el-button 
            size="medium" 
            type="success" 
            style="width:100%;" 
            @click="handleCasLogin"
          >
            使用学校账号登录
          </el-button>
        </div>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2025 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg, login } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import defaultSettings from '@/settings';
import request from '@/utils/request'

export default {
  name: "Login",
  data() {
    return {
      codeUrl: "",
      cookiePassword: "",
      // 验证码的文本值，用于验证
      captchaText: "",
      loginForm: {
        username: "admin",
        password: "admin123",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // CAS开关
      casEnabled: defaultSettings.casEnabled,
      // CAS服务端地址
      casLoginUrl: defaultSettings.casLoginUrl,
      // 注册开关
      register: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  methods: {
    getCode() {
      this.codeUrl = ""; // 清空验证码图片
      // 清除本地验证码文本
      this.captchaText = "";
      
      // 从后端获取验证码
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      }).catch(err => {
        console.error("获取验证码失败:", err);
        this.$message.error("验证码获取失败，将使用本地验证码");
        
        // 后端验证码获取失败，使用本地验证码作为备选
        this.generateLocalCaptcha();
      });
    },
    
    // 本地生成验证码（仅作为后备方案）
    generateLocalCaptcha() {
      // 生成4位随机验证码
      const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
      let code = '';
      for (let i = 0; i < 4; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      
      // 保存验证码文本用于后续验证
      this.captchaText = code;
      
      // 创建Canvas元素生成验证码图片
      const canvas = document.createElement('canvas');
      canvas.width = 100;
      canvas.height = 38;
      const ctx = canvas.getContext('2d');
      
      // 绘制背景
      ctx.fillStyle = '#f0f0f0';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      
      // 添加干扰线
      for (let i = 0; i < 3; i++) {
        ctx.strokeStyle = this.getRandomColor(150, 200);
        ctx.beginPath();
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.stroke();
      }
      
      // 添加干扰点
      for (let i = 0; i < 30; i++) {
        ctx.fillStyle = this.getRandomColor(0, 255);
        ctx.beginPath();
        ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI);
        ctx.fill();
      }
      
      // 绘制验证码
      ctx.font = 'bold 20px Arial';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      
      for (let i = 0; i < code.length; i++) {
        ctx.fillStyle = this.getRandomColor(10, 100);
        ctx.fillText(
          code.charAt(i), 
          20 + i * 20, 
          canvas.height / 2 + Math.random() * 6 - 3
        );
      }
      
      // 转换为图片URL
      this.codeUrl = canvas.toDataURL('image/png');
      this.loginForm.uuid = "temp-uuid-" + new Date().getTime();
      this.captchaEnabled = true;
    },
    
    // 生成随机颜色
    getRandomColor(min, max) {
      const r = Math.floor(Math.random() * (max - min) + min);
      const g = Math.floor(Math.random() * (max - min) + min);
      const b = Math.floor(Math.random() * (max - min) + min);
      return `rgb(${r},${g},${b})`;
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // 只有在使用本地生成的验证码时才进行前端验证
          if (this.captchaText && this.captchaEnabled && this.loginForm.code.toLowerCase() !== this.captchaText.toLowerCase()) {
            this.$message.error("验证码错误");
            this.getCode(); // 刷新验证码
            return;
          }
          
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }

          // 使用RuoYi-Vue原生Vuex store登录方法
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    },
    handleCasLogin() {
      // 跳转到CAS登录页面
      window.location.href = process.env.VUE_APP_BASE_API + "/cas/login";
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
.login-code-tip {
  font-size: 12px;
  text-align: right;
  color: #909399;
  margin-top: -15px;
  margin-bottom: 15px;
}
.login-code-loading {
  height: 38px;
  line-height: 38px;
  text-align: center;
  color: #909399;
  background: #f5f7fa;
  cursor: pointer;
  user-select: none;
  border-radius: 4px;
}
</style>
